package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;

@WebServlet(name = "UpdateBoardShortcutsControllerServlet", urlPatterns = "/UpdateBoardShortcutsControllerServlet")
public class UpdateBoardShortcutsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4152213277308329811L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (request.getParameter("restoreDefaults") != null) {
				user.getPreferences().setUseBoardShortcuts(false);
				user.getPreferences().store();
				response.sendRedirect(Configuration.getInstance().getRoot() + "/Pages/customise-board-shortcuts.jsp");
				return;
			}

			List<Board> boards = Boards.getAuthorisedBoards(user, false);

			List<Integer> boardShortcuts = new ArrayList<Integer>();

			for (Board board : boards) {

				String show = request.getParameter("show" + board.getBoardId());

				if (show != null) {
					boardShortcuts.add(board.getBoardId());
				}
			}

			user.getPreferences().setBoardShortcuts(boardShortcuts);
			user.getPreferences().setUseBoardShortcuts(true);
			user.getPreferences().store();

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Pages/customise-board-shortcuts.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}